package cn.tedu.API;
/**
 * @Author 金帮嘉诚
 * @Date 2021-06-16 周三 10:10
 */
/*本类用于练习字符串的拼接*/

/**
 * 知识点：
 */
public class TestString {
    public static void main(String[] args) {
        //1.
        String s = "abcdefghijklmnopqrstuvwxyz";
        method(s);
        System.out.println("==============================================");
        method2(s);
    }

    //
    private static void method(String s) {
        //拼接10000次
        //
        String result = "";
        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            result += s;
        }
        long t2 = System.currentTimeMillis();

        System.out.println("result = " + result);
        System.out.println("(t2-t1)+\"ms\" = " + (t2 - t1) + "ms");
    }

    private static void method2(String s) {
        //
        /*优化1：创建并使用可变字符序列对象StringBuffer/StringBuilder*/
        StringBuffer sb1 = new StringBuffer("");
        StringBuilder sb2 = new StringBuilder("");

        //返回19700101午夜开始至今过去的时间，单位毫秒

        long t1 = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            /*优化2：我们不再使用+拼接，而是使用append（）*/
            sb1.append(s);
//            sb2.append(s);
        }
        long t2 = System.currentTimeMillis();

        System.out.println("s = " + s);//不变
        System.out.println("sb1 = " + sb1);//打印拼接后字符串，底层重写了toString()
//        System.out.println("sb2 = " + sb2);//打印拼接后字符串，底层重写了toString()
        System.out.println("sb1.toString() = " + sb1.toString());
//        System.out.println("sb2.toString() = " + sb2.toString());
        System.out.println("(t2-t1) = " + (t2 - t1));

    }
}
